using BackData;
using Domain;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Quality;

namespace Team.API.Applocation.Hanldler.Quality
{
    /// <summary>
    /// 删除质检工单处理器
    /// </summary>
    public class DeleteQualityHandler : IRequestHandler<DeleteQualityCommand, APIResult<int>>
    {
        private readonly IRepository<Qualitymodel> _qualiRep;
        private readonly ILogger<DeleteQualityHandler> _logger;

        public DeleteQualityHandler(
            IRepository<Qualitymodel> qualiRep,
            ILogger<DeleteQualityHandler> logger)
        {
            _qualiRep = qualiRep;
            _logger = logger;
        }

        public async Task<APIResult<int>> Handle(DeleteQualityCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 1. 查询质检工单是否存在
                var quality = await _qualiRep.GetByIdAsync(request.Id);
                if (quality == null || quality.IsDel)
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.Fail,
                        Message = "质检工单不存在或已删除",
                        Result = 0
                    };
                }

                // 2. 逻辑删除
                quality.IsDel = true;
                quality.Updatetime = DateTime.Now;

                // 3. 执行逻辑删除
                _logger.LogInformation($"在{DateTime.Now}删除了质检工单ID:{request.Id}");
                var result = await _qualiRep.UpdateAsync(quality);

                if (result > 0)
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.OK,
                        Message = "质检工单删除成功",
                        Result = result
                    };
                }
                else
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.Fail,
                        Message = "质检工单删除失败",
                        Result = result
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"删除质检工单失败: {ex.Message}");
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = $"删除质检工单失败: {ex.Message}",
                    Result = 0
                };
            }
        }
    }
}
